package com.zqs.compareface.server.camstream;

import com.zqs.compareface.controller.StreamController;
import com.zqs.compareface.server.commit.CommitApiOrLocal;
import com.zqs.compareface.utils.impl.ImageToBase64Util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;

import java.awt.image.BufferedImage;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Program: face
 * @Description:
 * @Author: zqs
 * @Create： 2021-08-09-16:41
 */
public class CamStreamPullScreenshots extends Thread {
    protected final Log log = LogFactory.getLog(getClass());
    private String streamURL = StreamController.STREAM_URL;// 流地址

    public void setStreamURL(String streamURL) {
        this.streamURL = streamURL;
    }
    public void getScreen() {
        Date nowTime = new Date(System.currentTimeMillis());
        SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        /**
         * 判断采取哪种格式的图片做后续处理
         */
            //获取视频源
            FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(streamURL);
            grabber.setImageWidth(640);
            grabber.setImageHeight(480);
            //开始获取视频数据
            try {
                grabber.start();
            } catch (Exception e) {
                try {
                    //一次重启尝试
                    grabber.start();
                } catch (Exception e2) {
                    try {
                        throw e;
                    } catch (FFmpegFrameGrabber.Exception exception) {
                        exception.printStackTrace();
                    }
                }
            }
            try {
                while (grabber != null) {
                    System.out.println(sdFormatter.format(System.currentTimeMillis()));
                    Frame videoPic = grabber.grabImage();
                    if (videoPic != null) {
                        /**
                         * 转为BufferedImage类型
                         */
                        BufferedImage bufferedImage = new Java2DFrameConverter().getBufferedImage(videoPic);
                        /**
                         * 通过Util工具转码为base64
                         */
                        new CommitApiOrLocal().preparingData(ImageToBase64Util.convertBase64(bufferedImage),"luogang");
                    }
                }
                grabber.stop();
            } catch (FFmpegFrameGrabber.Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    grabber.close();
                } catch (FrameGrabber.Exception e) {
                    e.printStackTrace();
                }
            }
        }
}
